# dashboard.py
import numpy as np
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
from ai_transaction_detector import AITransactionDetector
import joblib
import os
from datetime import datetime

st.set_page_config(page_title="DBGuardian - 事务监控面板", layout="wide")
st.title("🛡️ DBGuardian：AI 长事务检测仪表盘")


# 加载模型
@st.cache_resource
def load_model():
    if os.path.exists("transaction_model.pkl"):
        return joblib.load("transaction_model.pkl")
    return None


model = load_model()


# 加载日志
@st.cache_data
def load_logs():
    if os.path.exists("training_logs.csv"):
        df = pd.read_csv("training_logs.csv")
        df['timestamp'] = pd.to_datetime('now') - pd.to_timedelta(np.random.randint(0, 1000, size=len(df)), unit='m')
        return df
    return pd.DataFrame()


logs_df = load_logs()

# === 1. 实时检测 ===
st.header("🔍 实时长事务检测")
with st.form("tx_form"):
    st.subheader("输入事务信息")
    duration = st.number_input("执行时长 (秒)", min_value=0, value=30)
    wait_time = st.number_input("等待时间 (毫秒)", min_value=0, value=100)
    rows = st.number_input("影响行数", min_value=0, value=100)
    locks = st.number_input("锁数量", min_value=0, value=2)

    submitted = st.form_submit_button("检测风险")
    if submitted and model is not None:
        detector = AITransactionDetector()
        new_tx = {
            "duration_sec": duration,
            "wait_time_ms": wait_time,
            "rows_affected": rows,
            "lock_count": locks
        }
        result = detector.predict(new_tx)

        if result["is_long_running"]:
            st.error(f"🚨 高风险事务！{result['suggestion']} (置信度: {result['confidence']:.2f})")
        else:
            st.success(f"✅ 低风险事务：{result['suggestion']}")

# === 2. 日志分析 ===
if not logs_df.empty:
    st.header("📊 历史事务分析")

    col1, col2 = st.columns(2)

    with col1:
        fig, ax = plt.subplots()
        logs_df['duration_sec'].hist(bins=20, ax=ax, color='skyblue')
        ax.set_title("事务时长分布")
        ax.set_xlabel("时长 (秒)")
        st.pyplot(fig)

    with col2:
        st.metric("总事务数", len(logs_df))
        st.metric("平均时长", f"{logs_df['duration_sec'].mean():.1f}s")
        high_risk = (logs_df['duration_sec'] > 300).sum()
        st.metric("高风险事务", high_risk)

    st.dataframe(logs_df)